<template>
    <d2-container>
        <el-button-group>
            <el-button type="primary" icon="el-icon-refresh" size="small" @click="getMenuTree">刷新</el-button>
            <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="add">添加</el-button>
            <el-button type="primary" icon="el-icon-aim" :disabled="currentId == 0" size="small" @click="cancel">取消
            </el-button>
        </el-button-group>
        <el-popover placement="top-start" title="温馨提示" width="400" trigger="hover">
            <li>请选择菜单类节点后添加模板</li>
            <el-button slot="reference" size="small" icon="el-icon-info" style="float:right">操作提示</el-button>
        </el-popover>
        <el-row :gutter="20">
            <el-col :span="8" style="margin-top:15px;">
                <el-card shadow="hover" v-loading="treeLoading">
                    <el-tree ref="tree" class="filter-tree" node-key="id" highlight-current
                        :expand-on-click-node="false" :data="menuTree" :props="defaultProps" @node-click="getMenuData"
                        :default-expand-all="expandAll" :default-expanded-keys="expandKeys">
                        <span class="custom-tree-node" slot-scope="{ node, data }" render-after-expand>
                            <span>
                                <d2-icon :name="data.icon" style="margin-right:10px;" v-if="data.typeEnum != '/'" />
                                {{ data.label }}
                            </span>
                            <span style="color:#a7a7a7;" v-if="data.typeEnum != '/'">
                                {{data.typeEnum}}
                            </span>
                        </span>
                    </el-tree>
                </el-card>
            </el-col>
            <el-col :span="16" style="margin-top:15px;">
                <el-card shadow="hover">
                    <!-- 表格表体 -->
                    <ec-table :data="tabledata" :loading="loading">
                        <el-table-column prop="templateName" header-align="center" align="center" show-overflow-tooltip
                            label="模板名称">
                        </el-table-column>
                        <el-table-column prop="templateCode" header-align="center" align="center" show-overflow-tooltip
                            label="模板编号">
                        </el-table-column>
                        <el-table-column prop="moduleValue" header-align="center" align="center" show-overflow-tooltip
                            label="模块编号">
                        </el-table-column>
                        <el-table-column prop="pkFile" header-align="center" align="center" show-overflow-tooltip
                            label="文件">
                        </el-table-column>
                        <el-table-column prop="version" header-align="center" align="center" show-overflow-tooltip
                            label="版本">
                        </el-table-column>
                        <el-table-column prop="note" header-align="center" align="center" show-overflow-tooltip
                            label="描述">
                        </el-table-column>
                        <el-table-column fixed="right" header-align="center" align="center" width="120" label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="deleteHandle(scope.row.pkTemplate)"
                                    class="el-icon-delete" v-if="isAuth()">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </ec-table>
                </el-card>
                <el-card shadow="hover" style="margin-top:20px" v-if="addVisible">
                    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                        label-width="80px">
                        <el-form-item label="模板名称" prop="templateName">
                            <el-input v-model="dataForm.templateName" placeholder="模板名称" maxlength="30" show-word-limit disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="菜单编号" prop="moduleValue">
                            <el-input v-model="dataForm.moduleValue" placeholder="请选择菜单" maxlength="30" show-word-limit
                                disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="文件" prop="pkFile">
                            <el-upload class="upload-demo" drag :action="uploadUrl" :data="uploadConfig"
                                :headers="headers" :on-error="uploadOnError" :on-progress="uploadOnProgress"
                                :on-change="uploadOnChange" :on-success="uploadOnSuccess">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="描述" prop="note">
                            <el-input v-model="dataForm.note" placeholder="描述" maxlength="200" show-word-limit>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submit" :loading="submitLoading">提交</el-button>
                            <el-button @click="reset">清空</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>

    </d2-container>
</template>

<script>
    import * as menuService from "@/api/upms/menu";
    import * as userShortcutService from '@/api/upms/usershortcut'
    import * as dataimporttemplateService from '@/api/report/dataimporttemplate'

    import util from '@/libs/util'
    export default {
        name: "report-import-template-index",
        data() {
            return {
                treeLoading: false,
                expandAll: false,
                currentId: 0,
                menuList: [],
                expandKeys: ['-1'],
                menuTree: [{
                    id: '-1',
                    label: '菜单目录',
                    parentModuleId: '0',
                    typeEnum: '/',
                    icon: '',
                    children: []
                }],
                defaultProps: {
                    children: 'children',
                },
                typeOptions: [{
                    value: '0',
                    label: "模块"
                }, {
                    value: '1',
                    label: "目录"
                }, {
                    value: '2',
                    label: "菜单"
                }, {
                    value: '3',
                    label: "按钮"
                }],
                treeProps: {
                    parent: 'pid',
                    value: 'id',
                    label: 'label',
                    children: 'children',
                },
                menuform: {
                    moduleId: "",
                    parentModuleId: "0",
                    moduleName: "",
                    moduleIcon: "",
                    moduleSort: 0,
                    moduleType: '0',
                    modulePath: '',
                    moduleAuthority: '',
                    moduleValue: '',
                    moduleDescription: ''
                },
                addVisible: false,
                loading: false,
                tabledata: [],
                dataForm: {
                    pkTemplate: 0,
                    templateName: '',
                    templateCode: '',
                    moduleValue: '',
                    pkFile: '',
                    version: '',
                    note: '',
                },
                dataRule: {
                    templateName: [{
                        required: true,
                        message: '模板名称不能为空',
                        trigger: 'change'
                    }],
                    moduleValue: [{
                        required: true,
                        message: '模块编号不能为空',
                        trigger: 'change'
                    }],
                    pkFile: [{
                        required: true,
                        message: '文件不能为空',
                        trigger: 'change'
                    }],
                    note: [{
                        required: true,
                        message: '描述不能为空',
                        trigger: 'change'
                    }],
                },
                uploadConfig: {
                    fileSpace: '1176328668683833346',
                    storeType: 'local',
                    filePath: ''
                },
                submitLoading: false
            }
        },
        computed: {
            // 设置请求头
            headers() {
                return {
                    // 设置Content-Type类型为multipart/form-data
                    'ContentType': 'multipart/form-data',
                    // 设置token
                    'Authorization': util.cookies.get('token_type') + " " + util.cookies.get('token')
                }
            },
            // 设置上传地址
            uploadUrl() {
                // baseURL是服务器的路径，也是axios的基本路径
                return process.env.VUE_APP_API + '/fs/local/saveFile'
            }
        },
        components: {},
        created() {
            this.getMenuTree();
        },
        methods: {
            getMenuTree() {
                this.treeLoading = true;
                let params = {
                    moduleType: '0,1,2'
                }
                menuService.getMenuTree(params).then(data => {
                    if (data) {
                        let keys = []
                        data.forEach(item => {
                            keys.push(item.id)
                        })
                        this.expandKeys = [...keys, ...this.expandKeys]
                        this.menuTree[0].children = data;
                    }
                    this.treeLoading = false;
                });
            },
            getMenuData(data) {
                let code = data.id;
                if (data.type != '2') {
                    this.dataForm.moduleValue = ''
                    this.$message.warning("请选择菜单！");
                    return
                }
                if (code == '-1') {
                    this.currentId = data.parentModuleId
                    return
                }
                menuService.getMenu(code).then(data => {
                    this.menuform = {
                        moduleId: data.moduleId,
                        parentModuleId: data.parentModuleId,
                        parentModuleName: data.parentModuleName,
                        parentModuleValue: data.parentModuleValue,
                        moduleName: data.moduleName,
                        moduleIcon: data.moduleIcon,
                        perms: data.perms,
                        moduleSort: data.moduleSort,
                        moduleType: data.moduleType,
                        modulePath: data.modulePath,
                        moduleAuthority: data.moduleAuthority,
                        moduleValue: data.moduleValue,
                        moduleDescription: data.moduleDescription
                    };
                    this.currentId = code;

                    this.dataForm.moduleValue = data.moduleValue
                    this.getDataTable(data.moduleValue)
                });

            },
            // 获取数据列表
            getDataTable(moduleValue) {
                this.loading = true
                let query = {
                    moduleValue: moduleValue
                };
                dataimporttemplateService.getDataImportTemplateList(query).then(data => {
                    this.tabledata = data;
                    this.loading = false;
                }).catch((res) => {
                    this.loading = false;
                });
            },
            add() {
                this.dataForm = {
                    pkTemplate: 0,
                    templateName: '',
                    templateCode: '',
                    moduleValue: this.menuform.moduleValue,
                    pkFile: '',
                    version: '',
                    note: '',
                }
                this.addVisible = true
            },
            edit() {
                if (this.currentId == 0) {
                    this.$message.error('请从左侧选择菜单！');
                    return
                }
                this.addVisible = true;
            },
            cancel() {
                this.addVisible = false;
                this.currentId = 0;
                this.getMenuTree();
            },
            submit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.submitLoading = true
                        var params = {
                            'pkTemplate': this.dataForm.pkTemplate || undefined,
                            'templateName': this.dataForm.templateName,
                            'templateCode': this.dataForm.templateCode,
                            'moduleValue': this.dataForm.moduleValue,
                            'pkFile': this.dataForm.pkFile,
                            'version': this.dataForm.version,
                            'note': this.dataForm.note,
                            'revision': this.dataForm.revision,
                        }
                        var tick = !this.dataForm.pkTemplate ? dataimporttemplateService.addDataImportTemplate(
                            params) : dataimporttemplateService.updateDataImportTemplate(params)
                        tick.then(data => {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.submitLoading = false
                                    // this.visible = false
                                    this.getDataTable(this.menuform.moduleValue)
                                    this.addVisible = false
                                }
                            })
                        }).catch((res) => {
                            this.submitLoading = false
                        })
                    }
                })
            },
            // 删除
            deleteHandle(id) {
                if (id) {
                    this.$confirm("确认删除？", "确认信息", {
                        distinguishCancelAndClose: true,
                        confirmButtonText: "删除",
                        cancelButtonText: "取消"
                    }).then(() => {
                        dataimporttemplateService.delDataImportTemplate(id).then(() => {
                            this.getDataTable(this.menuform.moduleValue);
                        });
                    });
                }
            },
            reset() {
                this.menuform = {
                    moduleId: "",
                    parentModuleId: "",
                    parentModuleName: "",
                    parentModuleValue: "",
                    moduleName: "",
                    moduleIcon: "",
                    moduleSort: 0,
                    moduleType: '0',
                    modulePath: "",
                    moduleAuthority: "",
                    moduleValue: "",
                    moduleDescription: "",
                };
                this.dataForm = {
                    pkTemplate: 0,
                    templateName: '',
                    templateCode: '',
                    moduleValue: '',
                    pkFile: '',
                    version: '',
                    note: '',
                }
            },
            uploadOnProgress(e, file) { //开始上传
                // console.log(e.percent, file)
            },
            uploadOnChange(file) {
                // console.log("——————————change——————————")
                // console.log(file)
                if (file.status == 'ready') {
                    // console.log("ready")
                } else if (file.status == 'fail') {
                    this.$message.error("上传出错，请刷新重试！")
                }
            },
            uploadOnSuccess(e, file) { //上传附件
                // console.log("——————————success——————————")
                this.$message.success("上传成功")
                this.dataForm.templateName = file.name
                this.dataForm.pkFile = e.data.fileId
            },
            uploadOnError(e, file) {
                // console.log("——————————error——————————")
                // console.log(e)
                this.$message.error("上传出错，请刷新重试！")
            },

        },

    };
</script>

<style scoped>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 13px;
        padding-right: 8px;
    }
</style>